package routers

import (
	"app/controllers"
	"app/pkg/logger"
	"app/routers/middleware"
	"bytes"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

func LoggerMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()

		// 请求前的逻辑
		fmt.Printf("开始处理请求: %s %s  \n", c.Request.Method, c.Request.URL.Path)

		// 打印请求参数
		queryParams := c.Request.URL.Query()
		query := "?"
		for key, values := range queryParams {
			for _, value := range values {
				query += key + "=" + value + "&"
			}
		}
		fmt.Printf("参数:%s:", query)
		// 读取请求Body的值
		body, err := ioutil.ReadAll(c.Request.Body)
		if err != nil {
			log.Println("读取请求Body失败:", err)
		}

		// 打印请求Body的值
		fmt.Printf("请求Body的值: %s\n", body)
		// 将读取的Body数据重新写回到Request.Body中，以便后续处理程序读取
		c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body))

		// 用于捕获响应的内容
		bodyWriter := &bodyWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer}
		c.Writer = bodyWriter

		c.Next()
		// 请求后的逻辑
		fmt.Printf("请求处理完成: %s %s，耗时: %v\n", c.Request.Method, c.Request.URL.Path, time.Since(start))
		//执行完才有响应
		fmt.Printf("响应内容: %s\n", bodyWriter.body.String())

	}
}

// bodyWriter 用于捕获响应的内容
type bodyWriter struct {
	gin.ResponseWriter
	body *bytes.Buffer
}

// Write 用于拦截响应内容并保存到缓冲区
func (w *bodyWriter) Write(b []byte) (int, error) {
	w.body.Write(b)
	return w.ResponseWriter.Write(b)
}

func Routers() *gin.Engine {

	r := gin.Default()
	// 调用日志组件
	r.Use(gin.LoggerWithConfig(logger.LoggerToFile()))
	r.Use(logger.Recover)
	//2.限流rate-limit 中间件
	r.Use(middleware.LimitHandler())
	//3.判断接口是否合法
	//r.Use(middleware.ValidityAPi())

	//r.Use(LoggerMiddleware())
	// 在中间添加路由信息
	// 定义用户路由组
	users := r.Group("v2/users") // 使用 user 变量接收，之后的user子路由直接使用 user 来定义
	{

		users.POST("/save", controllers.UserController{}.Save)
		users.POST("/login", controllers.UserController{}.Login)
	}

	// 定义角色路由组
	role := r.Group("/roles")
	{
		role.GET("/roleLogin", func(c *gin.Context) {
			c.JSON(http.StatusOK, gin.H{
				"msg": "角色登录",
			})
		})
	}

	web := r.Group("v2/web") // 使用 user 变量接收，之后的user子路由直接使用 user 来定义
	{

		web.GET("/album", func(c *gin.Context) {
			controllers.GetAlbums(c)
		})
		web.GET("/getList", func(c *gin.Context) {
			controllers.WebInfoController{}.GetList(c)
		})
		web.POST("/SearchList", func(c *gin.Context) {
			controllers.WebInfoController{}.SearchList(c)
		})
		web.GET("/GetSearchList", func(c *gin.Context) {
			controllers.WebInfoController{}.GetSearchList(c)
		})
		web.POST("/UploadFile", func(c *gin.Context) {
			controllers.WebInfoController{}.UploadFile(c)
		})
		web.GET("/DownloadFile", func(c *gin.Context) {
			controllers.WebInfoController{}.DownloadFile(c)
		})
		web.GET("/StreamChat", func(c *gin.Context) {
			controllers.ChatController{}.StreamChat(c)
		})

		web.GET("/WsHandler", func(c *gin.Context) {
			controllers.ChatController{}.WsHandler(c)
		})

	}

	redirect := r.Group("/web")
	{
		redirect.GET("/", func(c *gin.Context) {
			//使用Context调用Redirect()⽀持内部和外部的重定向
			//重定向到外部
			c.Redirect(http.StatusMovedPermanently, "http://124.220.104.235/web/fund/MyFund")
			//重定向到内部
			//c.Redirect(http.StatusMovedPermanently, "/内部接口/路径")
		})

		web.POST("/job/save", func(c *gin.Context) {
			controllers.JobController{}.Save(c)
		})
		web.GET("/job/getById", func(c *gin.Context) {
			controllers.JobController{}.GetById(c)
		})
		web.POST("/job/batchSave", func(c *gin.Context) {
			controllers.JobController{}.BatchSave(c)
		})

	}

	return r
}
